package es.cea.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import es.cea.helpers.EstadisticasHelper;

@WebServlet("/libros")
public class ListaLibrosServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
    private Connection conexion;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession ses = request.getSession();
		
		EstadisticasHelper.realizarEstadistica(request);
		
		System.out.println("Lista de libros");
		System.out.println(ses.getAttribute("nombreAdmin"));
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conexion = DriverManager.getConnection ("jdbc:mysql://localhost/libreria","root", "root");
			Statement s = conexion.createStatement();
			
			ResultSet rs = s.executeQuery ("select * from libros");  
			List<Libro> libros = new ArrayList<Libro>();
			while (rs.next())  
			{  
				libros.add(new Libro(rs.getInt(1),rs.getString (2), rs.getDate (3),rs.getInt(4)));
			}  
			
			PrintWriter writer = response.getWriter();
			writer.println("<html> <head> " + ses.getAttribute("nombreAdmin") + "<br></head><body>");
			for(Libro libro:libros){
				writer.println(libro.nombre + "&nbsp <a href = 'LibroEdit?id="+ libro.id  +"'>Editar</a> &nbsp &nbsp <a href = 'LibroDetail?id=" + libro.id + "'>Detalles</a><br> <br>");
			}
			writer.println("</body> </html>");
			writer.close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e){
			e.printStackTrace();
		}
		

		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
	
}
